package com.carryGo.dao.dp;

import com.carryGo.utils.DBUtilsHelper;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * ClassName:UserDao
 * package:gouban
 * Desription:
 * sql方法
 * @Date:2020/8/23 17:13
 * @Author: 邓攀
 */
public class UserDao {

    public static QueryRunner runner = null;
    static {
        runner = new DBUtilsHelper().getRunner();
    }

    //获取数据源连接
    public Connection getConnection() throws SQLException {
        return runner.getDataSource().getConnection();
    }

    //关闭数据源连接
    public void CloseConnection() throws SQLException {
        runner.getDataSource().getConnection().close();
    }

    public <T> T findBean(Class<T> beanClass, String sql, Object... params) {
        try {
            return runner.query(sql, new BeanHandler<T>(beanClass), params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public <T> T findBean(Class<T> beanClass, String sql) {
        try {
            return runner.query(sql, new BeanHandler<T>(beanClass));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public <T> List<T> findList(Class<T> beanClass, String sql, Object... params) {
        try {
            return runner.query(sql, new BeanListHandler<T>(beanClass), params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public <T> List<T> findList(Class<T> beanClass, String sql) {
        try {
            return runner.query(sql, new BeanListHandler<T>(beanClass));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public long getCount(String sql, Object... params) {
        try {
            return (long) runner.query(sql, new ScalarHandler<Long>(), params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public int count(String sql) {
        try {
            Long l = (Long) runner.query(sql, new ScalarHandler<>());
            return Integer.parseInt(l.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public int update(String sql, Object... params) {
        try {
            return runner.update(sql, params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public int[] batch(String sql, Object[][] params) {
        try {
            return runner.batch(sql, params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

}
